package com.wx.service.impl;

import java.util.List;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.exception.ServiceException;
import com.wx.mapper.CommodityMapper;
import com.wx.mapper.UserMapper;
import com.wx.pojo.Commodity;
import com.wx.pojo.User;
import com.wx.service.CommodityService;

@Service
public class CommodityServiceImpl implements CommodityService{

	@Autowired
	private CommodityMapper commodityMapper;
	@Autowired
	private UserMapper userMapper;

	//添加商品
	@Override
	public void insertCommodity(Commodity commodity,String token) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
		//从数据库查询该token
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("token", token);
		User user = userMapper.selectOne(queryWrapper);
		if (user==null||!user.getToken().equals(token)) new ServiceException("身份信息无效,请登录!");

		//验证参数
		if(commodity.getUserId()==null
				||Strings.isEmpty(commodity.getName())
				||Strings.isEmpty(commodity.getDes())
				||Strings.isEmpty(commodity.getUnit())) new IllegalArgumentException("参数未填写完整");
		//插入数据
		commodityMapper.insert(commodity);
	}

	@Override
	public List<Commodity> findCommodityByUserId(String token) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
		//从数据库查询该token
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("token", token);
		User user = userMapper.selectOne(queryWrapper);
		if (user==null||!user.getToken().equals(token)) new ServiceException("身份信息无效,请登录!");
		//查看当前用户
		//查找当前用户已添加的商品
		return commodityMapper.findCommodityByUserId(user.getId());
	}

	@Override
	public void updateCommodityById(Commodity commodity, String token) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
		//从数据库查询该token
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("token", token);
		User user = userMapper.selectOne(queryWrapper);
		if (user==null||!user.getToken().equals(token)) new ServiceException("身份信息无效,请登录!");

		//验证参数
		if(commodity.getId()==null) new IllegalArgumentException("商品id为空");
		if(commodity.getUserId()==null
				||Strings.isEmpty(commodity.getName())
				||Strings.isEmpty(commodity.getDes())
				||Strings.isEmpty(commodity.getUnit())) new IllegalArgumentException("参数未填写完整");
		//修改数据
		try {
			commodityMapper.updateById(commodity);
		} catch (Exception e) {
			new ServiceException("系统错误，修改失败！");
		}
	}

}
